
/**
 * Copyright 2014-2020  the original author or authors.
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
package com.upb.webserver.account;

import com.upb.webserver.common.enums.TokenTypeEnum;
import com.upb.webserver.common.exception.WebServerException;
import com.upb.webserver.common.pojo.account.ImageToken;
import com.upb.webserver.common.pojo.base.BaseResponse;
import com.upb.webserver.common.returncode.ConstantCode;
import com.upb.webserver.common.tools.JsonUtils;
import com.upb.webserver.common.tools.TokenImgGenerator;
import com.upb.webserver.common.tools.WebServerTools;
import com.upb.webserver.token.TokenService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Log4j2
@RestController
@RequestMapping(value = "account")
public class AccountController {

    @Autowired
    private AccountService accountService;
    @Autowired
    private TokenService tokenService;
    private static final int PICTURE_CHECK_CODE_CHAR_NUMBER = 4;

    /**
     * 获取验证码
     */
    @GetMapping(value = "pictureCheckCode")
    public BaseResponse getPictureCheckCode() throws Exception {
        log.info("start getPictureCheckCode");

        // random code
        String checkCode = WebServerTools.randomString(PICTURE_CHECK_CODE_CHAR_NUMBER);

        String token = tokenService.createToken(checkCode, TokenTypeEnum.VERIFICATION_CODE.getId());
        log.info("new checkCode:" + checkCode);

        BaseResponse baseResponse = new BaseResponse(ConstantCode.SUCCESS);
        try {
            // 得到图形验证码并返回给页面
            String base64Image = TokenImgGenerator.getBase64Image(checkCode);
            ImageToken tokenData = new ImageToken();
            tokenData.setToken(token);
            tokenData.setBase64Image(base64Image);
            baseResponse.setData(tokenData);
            log.info("end getPictureCheckCode. baseResponse:{}", JsonUtils.objToString(baseResponse));
            return baseResponse;
        } catch (Exception e) {
            log.error("fail getPictureCheckCode", e);
            throw new WebServerException(ConstantCode.SYSTEM_EXCEPTION);
        }
    }
}
